<template>
  <Modal v-model="show" title="分配角色">
    <Transfer
        :data="data"
        :target-keys="targetKeys"
        :list-style="listStyle"
        :titles="['未分配角色', '已分配角色']"
        filterable
        :filter-method="filterMethod"
        @on-change="handleChange"></Transfer>

    <template #footer>
      <Button style="margin-right: 8px" @click="show = false">关闭</Button>
      <Button type="primary" @click="handleSave">保存</Button>
    </template>
  </Modal>
</template>
<script>
export default {
  props: {
    modelValue: {type: Boolean, required: true},
    userId: {type: Number, required: true},
  },
  data() {
    return {
      data: [],
      targetKeys: [],
      listStyle: {
        height: '500px',
      }
    }
  },
  emits: ["bind-role-ok"],
  created() {
     this.$api.queryUserBindRoles(this.userId).then(ret=>{
       if (ret.data.status) {
          this.data = ret.data.list.map(r => ({key: r.id, label: r.name, disabled: !r.state})) ;
          this.targetKeys = ret.data.list.filter(r => r.bind).map(r => r.id);
       }
     })
  },
  methods: {
    handleChange(newTargetKeys) {
      this.targetKeys = newTargetKeys;
    },
    filterMethod(data, query) {
      return data.label.indexOf(query) > -1;
    },
    handleSave() {
       // 获取 选中的角色，并进行保存
      this.$api.bindRole(this.userId, this.targetKeys).then(ret=> {
         if (ret.data.status) {
            // 关闭窗口、并通知父组件刷新数据
           this.$tips.success("操作成功") ;
           this.show = false ;
           this.$emit("bind-role-ok") ;
         }
      })
    }
  },
  computed: {
    show: {
      get() {
        return this.modelValue;
      },
      set(val) {
        this.$emit("update:model-value", val);
      }
    }
  },
}
</script>

<style>
.ivu-transfer {
  text-align: center;
}

.ivu-transfer-list-footer {
  border: none;
}

.ivu-transfer-list-content {
  text-align: left;
}
</style>
